import { useNavigate, useParams } from "react-router-dom";
import { useGetUserQuery } from "../../api/users";
import { Loader } from "../UI/loader";
import { Box, Button, Modal, Typography } from "@mui/material";
import s from "./styles.module.scss";
import { useGetPostQuery } from "../../api/posts";
import { PostCard } from "../UI/postCard";
import { useLazyGetTodosQuery } from "../../api/todos";
import { useState } from "react";
import { style } from "../../data/data";
import { UserMainInfo } from "../UI/userMainInfo";
import { styled } from "@mui/material/styles";
import MuiAccordion from "@mui/material/Accordion";
import MuiAccordionSummary from "@mui/material/AccordionSummary";
import MuiAccordionDetails from "@mui/material/AccordionDetails";
import ArrowForwardIosSharpIcon from "@mui/icons-material/ArrowForwardIosSharp";
import { useLazyGetAlbumsQuery, useLazyGetPhotosQuery } from "../../api/album";

const Accordion = styled((props) => (
  <MuiAccordion disableGutters elevation={0} square {...props} />
))(({ theme }) => ({
  border: `1px solid ${theme.palette.divider}`,
  marginTop: 20,
  "&:not(:last-child)": {
    borderBottom: 0,
  },
  "&:before": {
    display: "none",
  },
}));

const AccordionSummary = styled((props) => (
  <MuiAccordionSummary
    expandIcon={<ArrowForwardIosSharpIcon sx={{ fontSize: "0.9rem" }} />}
    {...props}
  />
))(({ theme }) => ({
  backgroundColor: "#1976d2",
  color: "white",
  flexDirection: "row-reverse",
  "& .MuiAccordionSummary-expandIconWrapper": {
    color: "white",
  },
  "& .MuiAccordionSummary-expandIconWrapper.Mui-expanded": {
    transform: "rotate(90deg)",
  },
  "& .MuiAccordionSummary-content": {
    marginLeft: theme.spacing(1),
  },
}));

const AccordionDetails = styled(MuiAccordionDetails)(({ theme }) => ({
  padding: theme.spacing(2),
  borderTop: "1px solid rgba(0, 0, 0, .125)",
}));

export const UserPage = () => {
  const navigate = useNavigate();

  const [open, setOpen] = useState(false);
  const [dataModal, setDataModal] = useState(null);
  const [todos, setTodos] = useState(false);
  const [info, setInfo] = useState(false);
  const [album, setAlbum] = useState(false);

  const [photos, setDataPhoto] = useState(null);

  const [expanded, setExpanded] = useState("panel1");

  const handleChange = (panel) => (event, newExpanded) => {
    setExpanded(newExpanded ? panel : false);
  };

  const { user } = useParams();
  const { data, isLoading, isError } = useGetUserQuery(user);
  const userId = data?.[0]?.id;
  const {
    data: postData,
    isLoading: loadPost,
    isError: errorPost,
  } = useGetPostQuery(userId);
  const [getTodos, { isLoading: loadTodos, isError: errorTodos }] =
    useLazyGetTodosQuery();
  const [getAlbums, { isLoading: loadAlbum, isError: errorAlbum }] =
    useLazyGetAlbumsQuery();

  const [getPhotos, { isLoading: loadPhotos, isError: errorPhotos }] =
    useLazyGetPhotosQuery();

  const handleOpen = async (func, funcBool) => {
    try {
      setOpen(true);
      const response = await func(userId);
      setDataModal(response.data);
      funcBool(true);
    } catch (error) {
      console.error("Error fetching surprise:", error);
    }
  };

  const handlePhotos = async (id) => {
    try {
      if (photos) {
        setDataPhoto(null);
      }
      const response = await getPhotos(id);
      setDataPhoto(response.data);
    } catch (e) {
      console.error("Error fetching surprise:", e);
    }
  };

  const handleClose = () => {
    setOpen(false);
    setTodos(false);
    setInfo(false);
    setAlbum(false);
    setDataModal(null);
  };

  return (
    <div className={s.user}>
      <Button
        variant="contained"
        sx={{ position: "fixed", right: 10 }}
        onClick={() => navigate("/search")}
      >
        Назад
      </Button>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Box
          sx={{
            ...style,
            width: todos || album ? "1000px" : "400px",
            height: album ? "500px" : "inherit",
          }}
        >
          {dataModal && todos ? (
            <ul className={s.user__modal__todos__list}>
              {dataModal.map((elem, key) => (
                <li key={key} className={s.user__modal__todos__list__item}>
                  <div className={s.user__modal__todos__item__title}>
                    {elem.title}
                  </div>
                  <div className={s.user__modal__todos__item__completed}>
                    {elem.completed ? (
                      <span style={{ color: "green" }}>Выполнено</span>
                    ) : (
                      <span style={{ color: "red" }}>Невыполнено</span>
                    )}
                  </div>
                </li>
              ))}
            </ul>
          ) : data && info ? (
            <UserMainInfo
              phone={data[0].phone}
              email={data[0].email}
              city={data[0].address.city}
              website={data[0].website}
              companyName={data[0].company.name}
              s={s}
            />
          ) : dataModal && album ? (
            <>
              {dataModal.map((elem, key) => (
                <Accordion
                  expanded={expanded === `panel${elem.id}`}
                  onChange={handleChange(`panel${elem.id}`)}
                  key={key}
                >
                  <AccordionSummary
                    aria-controls={`panel${elem.id}-content`}
                    id={`panel${elem.id}-header`}
                  >
                    <Typography
                      onClick={() => handlePhotos(elem.id)}
                      sx={{ width: "100%" }}
                    >
                      {elem.title}
                    </Typography>
                  </AccordionSummary>
                  <AccordionDetails>
                    {photos ? (
                      <div>
                        {photos.map((elem, key) => {
                          return <img src={elem.thumbnailUrl} key={key} />;
                        })}
                      </div>
                    ) : (
                      <Loader width={"100px"} height={"100px"} />
                    )}
                  </AccordionDetails>
                </Accordion>
              ))}
            </>
          ) : (
            <>
              <Loader width={"50px"} height={"50px"} />
            </>
          )}
        </Box>
      </Modal>
      {data ? (
        <Box sx={{ display: "flex" }}>
          <div className={s.user__left}>
            <img
              src="https://avatars.dzeninfra.ru/get-zen_doc/34175/pub_5cea2361585c2f00b5c9cb0b_5cea310a752e5b00b25b9c01/scale_1200"
              className={s.user__img}
            />
            <div className={s.user__info}>
              <div className={s.user__info__name}>{data[0].name}</div>
              <div className={s.user__info__username}>{data[0].username}</div>
              <ul className={s.user__info__list}>
                <li>
                  <Button
                    variant="contained"
                    onClick={() => handleOpen(getTodos, setInfo)}
                  >
                    Информация
                  </Button>
                </li>
                <li>
                  <Button
                    variant="contained"
                    onClick={() => handleOpen(getTodos, setTodos)}
                  >
                    Список дел
                  </Button>
                </li>
                <li>
                  <Button
                    variant="contained"
                    onClick={() => handleOpen(getAlbums, setAlbum)}
                  >
                    Альбомы
                  </Button>
                </li>
              </ul>
            </div>
          </div>

          <div className={s.user__right}>
            <div className={s.user__posts}>Посты:</div>

            {postData ? (
              <>
                <div className={s.user__posts__count}>
                  Всего: {postData.length}
                </div>
                {postData.map((elem, key) => (
                  <PostCard
                    id={elem.id}
                    key={key}
                    title={elem.title}
                    body={elem.body}
                    s={s}
                  />
                ))}
              </>
            ) : loadPost ? (
              <Loader width={"100px"} height={"100px"} />
            ) : null}
          </div>
        </Box>
      ) : isLoading ? (
        <Loader width={"100px"} height={"100px"} />
      ) : (
        <div>Ошибка</div>
      )}
    </div>
  );
};
